var NfcAdapter;
var NdefRecord;
var NdefMessage;
var _getCardNo;

export let isEnable;

export function initNFC() {
  if (uni.getSystemInfoSync().platform == "android") {
    return listenNFCStatus();
  }
  return false
}
export function readNFC(callback) {
  if (uni.getSystemInfoSync().platform == "android") {
    readData(callback);
  }
}
export function closeNFC() {
  if (uni.getSystemInfoSync().platform == "android") {
    closeReadAndWrite();
  }
}

function listenNFCStatus() {
  try {
    console.log("init nfc");
    var main = plus.android.runtimeMainActivity();
    var Intent = plus.android.importClass("android.content.Intent");
    var Activity = plus.android.importClass("android.app.Activity");
    var PendingIntent = plus.android.importClass("android.app.PendingIntent");
    var IntentFilter = plus.android.importClass("android.content.IntentFilter");
    NfcAdapter = plus.android.importClass("android.nfc.NfcAdapter");
    var nfcAdapter = NfcAdapter.getDefaultAdapter(main);

    if (nfcAdapter == null) {
      uni.showToast({
        title: "设备不支持NFC！",
        icon: "none",
      });
      return false;
    }

    isEnable = nfcAdapter.isEnabled()
    if (!nfcAdapter.isEnabled()) {
      uni.showToast({
        title: "请在系统设置中先启用NFC功能！",
        icon: "none",
      });
      return false;
    }

    var intent = new Intent(main, main.getClass());
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    // var pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
    //解决手机兼容性问题
    if (
      parseInt(new IntentFilter("android.os.Build.VERSION.SDK_INT").UUID) >=
      parseInt(new IntentFilter("android.os.Build.VERSION_CODES.S").UUID)
    ) {
      var pendingIntent = PendingIntent.getActivity(
        main,
        0,
        intent,
        PendingIntent.FLAG_IMMUTABLE
      );
    } else {
      var pendingIntent = PendingIntent.getActivity(
        main,
        0,
        intent,
        PendingIntent.FLAG_MUTABLE
      );
    }

    var ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
    ndef.addDataType("*/*");
    var intentFiltersArray = [ndef];
    var techListsArray = [
      ["android.nfc.tech.IsoDep"],
      ["android.nfc.tech.NfcA"],
      ["android.nfc.tech.NfcB"],
      ["android.nfc.tech.NfcF"],
      ["android.nfc.tech.Nfcf"],
      ["android.nfc.tech.NfcV"],
      ["android.nfc.tech.NdefFormatable"],
      ["android.nfc.tech.MifareClassic"],
      ["android.nfc.tech.MifareUltralight"],
    ];
    plus.globalEvent.addEventListener(
      "newintent",
      function () {
        setTimeout(handle_nfc_data1, 1000);
      },
      false
    );
    plus.globalEvent.addEventListener(
      "pause",
      function (e) {
        if (nfcAdapter) {
          nfcAdapter.disableForegroundDispatch(main);
        }
      },
      false
    );
    plus.globalEvent.addEventListener(
      "resume",
      function (e) {
        if (nfcAdapter) {
          //console.log('resume');
          nfcAdapter.enableForegroundDispatch(
            main,
            pendingIntent,
            intentFiltersArray,
            techListsArray
          );
        }
      },
      false
    );
    nfcAdapter.enableForegroundDispatch(
      main,
      pendingIntent,
      intentFiltersArray,
      techListsArray
    );
    return true
    console.log("end nfc");
  } catch (e) {
    return false
    console.log(e);
    console.error(e);
  }
}

function handle_nfc_data1() {
  NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
  NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
  var main = plus.android.runtimeMainActivity();
  var intent = main.getIntent();
  //console.log("action type:" + intent.getAction());
  if ("android.nfc.action.TECH_DISCOVERED" == intent.getAction()) {
    if (readyWriteData) {
      //__write(intent);
      readyWriteData = false;
    } else if (readyRead) {
      __read(intent);
      readyRead = false;
    }
  }
}

function __read(intent) {
  try {
    var content = "";
    waiting.setTitle("请勿移开标签\n正在读取数据...");

    // NFC id
		let bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
		let nfc_id = bytesToHexString(bytesId);
    console.log("nfc_id", nfc_id)

    // Get NDEF messages from the intent
    var messages = intent.getParcelableArrayExtra(
      NfcAdapter.EXTRA_NDEF_MESSAGES
    );
    console.log("messages", messages)

    if ((messages == null || messages?.length == 0) && nfc_id) {
      content = nfc_id;
    } else {
      for (var i = 0; i < messages.length; i++) {
        var message = messages[i];
        if (message != null) {
          var records = message.getRecords();
  
          // Loop through all NDEF records in the current NDEF message
          for (var j = 0; j < records.length; j++) {
            var recordType = String(records[j].getType());
            var payload = String(records[j].getPayload());
  
            // Decode payload to readable text
            payload = decodeURIComponent(escape(payload));
  
            let textEncoding = (payload[0] & 0x80) === 0 ? "UTF-8" : "UTF-16";
            let languageCodeLength = payload[0] & 0x3f;
            let textStartIndex = 1 + languageCodeLength;
            let text = payload
              .split(",")
              .slice(textStartIndex)
              .map((strItem) => String.fromCharCode(parseInt(strItem)))
              .join("");
            content = text;
          }
        }
      }
    }
    waiting.close();
    var tagid = String(content);
    if (typeof _getCardNo === "function") {
      _getCardNo(tagid);
    }
  } catch (e) {
    uni.showToast({
      title: e || '读取失败',
      icon: "none",
    });
  }
}

function bytesToHexString(inarray) {
  var i, j, x;
  var hex = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
  ];
  var out = "";
  for (j = 0; j < inarray.length; ++j) {
    x = parseInt(inarray[j]) & 0xff;
    i = (x >> 4) & 0x0f;
    out += hex[i];
    i = x & 0x0f;
    out += hex[i];
  }
  return out;
}

var waiting;
var readyWriteData = false;
var readyRead = false;

function readData(getCardNo) {
  readyRead = true;
  _getCardNo = getCardNo;
  waiting = plus.nativeUI.showWaiting("请靠近NFC标签！", {
    modal: false,
  });
}

function closeReadAndWrite() {
  readyWriteData = false;
  readyRead = false;

  if (waiting) {
    waiting.close();
  }
}
